package RequestHandler;

import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import Container.*;

public class SessionList {
    private static final int ITEM_PER_PAGE = 10;
    
    private Map<Integer, Integer> sl = new HashMap<Integer, Integer>();
    private Map<Integer, ArrayList<Item>> sr = new HashMap<Integer, ArrayList<Item>>();
    private final Lock slock = new ReentrantLock();
    private int curSid = 0;
    
    public int addSession(int uid) {
        slock.lock();
        int sid = getNewSid();
        try {
            sl.put(uid, sid);
        }
        finally {
            slock.unlock();
        }
        return sid;
    }
    
    public void addSearchResult(int sid, ArrayList<Item> items) {
        if (sr.containsKey(sid)) {
            sr.remove(sid);
        }
        sr.put(sid, items);
    }
    
    public void removeSearchResult(int sid) {
        if (sr.containsKey(sid)) {
            sr.remove(sid);
        }
    }
    
    public ArrayList<Item> getSearchResult(int sid, int page) {
        ArrayList<Item> items = new ArrayList<Item>();
        for (int i = (page - 1) * ITEM_PER_PAGE; i < page * ITEM_PER_PAGE && i < sr.get(sid).size(); i++) {
            items.add(sr.get(sid).get(i));
        }
        return items;
    }
    
    private int getNewSid() {
        curSid++;
        return curSid;
    }
    
    public void deleteSession(int sid) {
        slock.lock();
        try {
            sr.remove(sid);
            for (Map.Entry<Integer, Integer> entry : sl.entrySet()) {
                if (entry.getValue() == sid) {
                    sl.remove(entry.getKey());
                    break;
                }
            }
        }
        finally {
            slock.unlock();
        }    
    }
    
    public int getNumPage(int sid) {
        int numItem = sr.get(sid).size(); 
        if (numItem == 0) {
            return 1;
        }
        else if (numItem % ITEM_PER_PAGE == 0) {
            return numItem / ITEM_PER_PAGE;
        }
        else {
            return numItem / ITEM_PER_PAGE + 1;
        }
    }
    
    public int getNumReseult(int sid) {
        return sr.get(sid).size();
    }
    
    public boolean sessionExists(int uid, int sid) {
        boolean exists = false;
        slock.lock();
        try {
            exists = sl.containsKey(uid) && sl.get(uid)==sid;
        }
        finally {
            slock.unlock();
        }    
        return exists;
    }
}